import {post, put, reLaunch2Index} from './request.js'

export const wxLogin = async (data) => {
	uni.showLoading();
	const res = await post('auth/wxlogin', data);
	uni.hideLoading()
	
	var data = res.data;
	if (data != null) {
		uni.setStorageSync('userInfo', data);
		uni.reLaunch({
			url: '/pages/order/order'
		});
	}
}

export const logout = async() => {
	uni.removeStorageSync('userInfo');
	reLaunch2Index();
}

// 发起下单支付
export const wxPay = async (createOrderUrl, data) => {
	uni.showLoading();
	const res = await post(createOrderUrl, data);
	uni.hideLoading();
	if (res.success) {
		var orderId = res.data.orderId;
		// 调起微信支付
		uni.requestPayment({
			provider: 'wxpay', // 服务提提供商
			timeStamp: res.data.timeStamp, // 时间戳
			nonceStr: res.data.nonceStr, // 随机字符串
			package: res.data.prepayId,
			signType: res.data.signType, // 签名算法
			paySign: res.data.paySign, // 签名
			success: function (res) {
				// 支付成功
				post('express/order/complete-payment', {
					orderId: orderId
				}).then(result => {
					uni.reLaunch({
						url: '/pages/order/order_success'
					});
				});
			},
			fail: function (err) {
				
			}
		});
	}
}

// 接单
export const orderReceive = async (orderNo) => {
	uni.showLoading();
	const res = await put('order/receive',{orderNo});
	uni.hideLoading()
	if(res.code === 200){
		uni.showToast({
			icon: 'success',
			title: '接单成功'
		})
		return true
	}
	return false
}

// 确认送达
export const orderDeliver = async (orderNo) => {
	return new Promise((resovle) => {
		uni.showModal({
			title: '提示',
			content: '请确认已送达？',
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			async complete(e) {
				if(e.confirm){
					const res = await put('order/deliver',{orderNo});
					if(res.code === 200){
						uni.showToast({
							icon: 'success',
							title: '确认成功'
						})
						resovle(true)
					}
					resovle(false)
				}else{
					resovle(false)
				}
			}
		})
	})
}

export const orderComplete = async (orderNo) => {
	return new Promise((resovle) => {
		uni.showModal({
			title: '提示',
			content: '请尽量让客户确认完成订单，确定要帮用户确认订单？',
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			async complete(e) {
				if(e.confirm){
					const res = await put('order/complete',{orderNo});
					if(res.code === 200){
						uni.showToast({
							icon: 'success',
							title: '已完成订单'
						})
						resovle(true)
					}
					resovle(false)
				}else{
					resovle(false)
				}
			}
		})
	})
}

export const orderCompleteByUser = async (orderNo) => {
	return new Promise((resovle) => {
		uni.showModal({
			title: '提示',
			content: '确定订单已送达？',
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			async complete(e) {
				if(e.confirm){
					const res = await put('order/complete/user',{orderNo});
					if(res.code === 200){
						uni.showToast({
							icon: 'success',
							title: '已完成订单'
						})
						resovle(true)
					}
					resovle(false)
				}else{
					resovle(false)
				}
			}
		})
	})
}